﻿using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using SignalRHub.DTO;
using SignalRHub.Hubs;
using SignalRHub.Redis.Interface;

namespace SignalRHub.Host
{
    public class PerformanceVerificationHost : BackgroundService
    {
        private readonly ILogger<PerformanceVerificationHost> _logger;
        private readonly IHubContext<PerformanceVerificationHub> _hubContext;
        private readonly ICacheManager _cacheManager;
        private readonly CancellationTokenSource _cancellationTokenSource;

        /// <summary>
        /// 当前性能检验或标定主任务
        /// </summary>
        private const string Verify_CACHE_KEY = "Sms:Verify:CTITAN000120230526P00004";

        public PerformanceVerificationHost(ILogger<PerformanceVerificationHost> logger, ICacheManager cacheManager, IHubContext<PerformanceVerificationHub> hubContext)
        {
            _logger = logger;
            _cacheManager = cacheManager;
            _cancellationTokenSource = new CancellationTokenSource();
            _hubContext = hubContext;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("PerformanceVerificationHost is starting.");

            stoppingToken.Register(() =>
            {
                _logger.LogInformation("PerformanceVerificationHost is stopping.");
                _cancellationTokenSource.Cancel();
            });

            // 无限循环中占用 CPU 的无用代码，因此不推荐使用
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                // 实现你的服务逻辑
                //// 已记录统计结果
                //var notifyVerif = _cacheManager.Get<PvNotifyVerifCalibManagerDto>(Verify_CACHE_KEY);

                //await _hubContext.Clients.All.SendAsync("GetAutoStatResult", JsonConvert.SerializeObject(notifyVerif));

                //// _logger.LogInformation(JsonConvert.SerializeObject(notifyVerif));
                //// 等待10秒
                //await Task.Delay(TimeSpan.FromSeconds(5));
            }

            _logger.LogInformation("PerformanceVerificationHost has stopped.");
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            // 在这里写停止服务的逻辑，如取消任务，释放资源等等
            // ...
            await base.StopAsync(cancellationToken);
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            // 是否有性能检验任务
            bool isExistVerify = _cacheManager.IsSet(Verify_CACHE_KEY);

            if (isExistVerify)
            {
                await Task.Run(() =>
                {
                    // 展示给前端
                    while (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        // 已记录统计结果
                        var notifyVerif = _cacheManager.Get<PvNotifyVerifCalibManagerDto>(Verify_CACHE_KEY);

                        _hubContext.Clients.All.SendAsync("GetAutoStatResult", JsonConvert.SerializeObject(notifyVerif));

                        // _logger.LogInformation(JsonConvert.SerializeObject(notifyVerif));
                        // 等待10秒
                        Task.Delay(TimeSpan.FromSeconds(5));
                        //await this.ExecuteAsync(cancellationToken);
                    }
                });
            }
            else
            {
                await Task.CompletedTask;
            }
        }
    }
}